package com.example.dnm.controller;


import com.example.dnm.pojo.Role;
import com.example.dnm.pojo.User;
import com.example.dnm.resp.JsonResult;
import com.example.dnm.resp.JsonResultUtil;
import com.example.dnm.service.RoleService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @RequestMapping("findAllRole")
    public JsonResult findAllRole(Role role)
    {
        try {
            List<Role> list=roleService.findAllRole(role);
            PageInfo<Role> rolePageInfo = new PageInfo<>(list);
            return JsonResultUtil.getSuccessJson("成功",rolePageInfo);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return JsonResultUtil.getErrorJson("查询失败");
    }
    @RequestMapping("addRole")
    public JsonResult addRole(Role role)
    {
        try {
            if (role.getRolename()==null)
            {
                return JsonResultUtil.getErrorJson("角色名不能为空");
            }
            Role role1=roleService.findRoleByName(role);
            if (role1!=null)
            {
                return JsonResultUtil.getErrorJson("角色名重复");
            }
            roleService.addRole(role);
            return JsonResultUtil.getSuccessJson("添加成功");
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return JsonResultUtil.getErrorJson("添加失败");
    }
    @RequestMapping("editRole")
    public JsonResult editRole(Role role)
    {
        try {
            if(role.getRolename()==null)
            {
                return JsonResultUtil.getErrorJson("用户名不能为空");
            }
            Role role1=roleService.findRoleByName(role);
            if(role1!=null&!role1.getRolename().equals(role.getRolename()))
            {
                return JsonResultUtil.getErrorJson("用户名重复");
            }
            roleService.editRole(role);
            return JsonResultUtil.getSuccessJson("更新成功");

        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return JsonResultUtil.getErrorJson("更新失败");
    }
    @RequestMapping("deleteRole")
    public JsonResult deleteRole(Role role)
    {
        try {
            roleService.deleteRole(role);
            return JsonResultUtil.getSuccessJson("删除成功");
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return JsonResultUtil.getErrorJson("删除失败");
    }
}
